using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class AnyExistQueryResult<TSource> : ObservableSingleQueryResultBase<bool, TSource>
	{
		public AnyExistQueryResult(IEnumerable<TSource> source) : base(source)
		{
			OnSourceReset();
		}

		protected override void OnSourceReset()
		{
			TryApplyNewResultValue(SourceCount > 0);
		}

		protected override void OnSourceAdd(NotifyCollectionChangedEventArgs e)
		{
			TryApplyNewResultValue(true);
		}

		protected override void OnSourceReplace(NotifyCollectionChangedEventArgs e)
		{
			// result not affected
		}

		void TryApplyNewResultValue(bool value)
		{
			if (_anyExists != value)
			{
				_anyExists = value;
				OnPropertyChanged(ValueName);
			}
		}

		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}

		bool _anyExists;

		public override bool Value
		{
			get { return _anyExists; }
			set { throw new NotSupportedException(); }
		}
	}
}